$(function(){
	showCondition(true);
	var param = drgUI.setAjaxData(tabId) ;
	// 标题
	$("#"+ tabId + " #header").html(param.desc) ;
	
	var drgCode = param.pardrgCode ;
		
	// 定义加载对象。 divId、指标code、 指标名称、  数据data
	var caseCntCompareDep = {"id":"caseCntCompareDep","quotas":
		[{"code":"InCaseCnt","title":"入组病例数"},{"code":"PayGroupOverFeeCnt","title":"费用超标病例数"}],"data":{}} ;
	var profitLossDep = {"id":"profitLossDep","quotas":
		[{"code":"PayGroupExpectIncome","title":"预计收入"},{"code":"PayGroupActualFee","title":"实际支出"}],"data":{}} ;
	
	var avgFeeDepEch = {"id":"avgFeeDepEch","quotas":[{"code":"AvgFee","title":"次均费用"}],"data":{}} ;
	var feeDepEch = {"id":"feeDepEch","quotas":[{"code":"TechFee","title":"医技费"},{"code":"ManageFee","title":"管理费"}
		,{"code":"MedFee","title":"医疗费"},{"code":"NursFee","title":"护理费"}
			,{"code":"DrugMaterFee","title":"药品耗材费"}],"data":{}} ;
	var avgFeeAndFeeBqTab = {"id":"avgFeeAndFeeBqTab","quotas":[{"code":"AvgFee","title":"次均费用（元）"},
	                                                            {"code":"AvgDays","title":"平均住院日"},
	                                                            {"code":"DrugRatio","title":"药占比(%)"},
	                                                            {"code":"PayGroupOverFeeCnt","title":"费用超标病例数"},  {"code":"InCaseCnt","title":"病例数"} ],"data":{}} ;
	
	var caseFee = {"id":"caseFee","title":"病例费用","quotas": [{"code":"TotalFee","title":"总费用"}],"data":{}} ;
	// 科室病例分布
	var param1 = {"pardrgCode":drgCode,"monitorType":"dep","compareType":"std"} ;
	loadDataPayGroup(caseCntCompareDep,processCaseCntCompareDep,param1) ;
	// 科室结余
	var param2 = {"pardrgCode":drgCode,"monitorType":"dep"} ;
	loadDataPayGroup(profitLossDep,processProfitLossDep,param2) ;
	// 科室次均费用对比图
	loadDataPayGroup(avgFeeDepEch,processAvgFeeDep,param2) ;
	// 科室费用构成及对比图
	loadDataPayGroup(feeDepEch,processFeeDep,param1,avgFeeAndFeeBqTab) ;
	//病例分布特征
	findCaseDistributionFeatureDep();
}) 

/**
 * 
 * @@param caseCntCompareDep
 * @void
 * @ Discription:
 * @paygroupAnalysis_dep.js
 */
function processCaseCntCompareDep(caseCntCompareDep) {
	// 当数据均返回的时候开始拼装数据
	var paramEch = {"title":"科室病例及超标病例数对比","subtitle":paramTabPage[tabId].desc,"legend":{"x":50,"y":50,"data":["全部病例","超标病例"]},"series":[{"name":"全部病例","data":[]},{"name":"超标病例","data":[]}],"y":{"data":[]}};
	var depData = caseCntCompareDep.data.dep ;
	for(var i in depData) {
		paramEch.y.data.push(depData[i].ddesc) ;
		if(depData[i].InCaseCnt) {
			paramEch.series[0].data.push(depData[i].InCaseCnt) ;
		}
		if(depData[i].PayGroupOverFeeCnt) {
			paramEch.series[1].data.push(depData[i].PayGroupOverFeeCnt) ;
		}
	}
	paramEch.gridTop = '80' ;
	drawPayGroupBarChart(caseCntCompareDep.id,paramEch) ;
}

/**
 * 科室结余数据数据
 * @@param profitLossDep
 * @void
 * @ Discription:
 * @paygroupAnalysis_dep.js
 */
function processProfitLossDep(profitLossDep) {
	var legend = {"x":50,"y":50,
	        data:['预计结余(万元)', '实际支出(万元)', '预计收入(万元)']
	    } ;
		var paramEch = {"title":"科室预计结余图","subtitle":paramTabPage[tabId].desc,"legend":legend,
				"series":[{"name":"预计结余(万元)","data":[] },
				          {"name":"实际支出(万元)","data":[] },
				          {"name":"预计收入(万元)","data":[] }],"y":{"data":[]}};
		var depData = profitLossDep.data.dep ;
		for(var o in depData) {
			paramEch.series[0].data.push((depData[o].PayGroupExpectIncome-depData[o].PayGroupActualFee).toFixed(2)) ;
			paramEch.series[1].data.push(-depData[o].PayGroupActualFee.toFixed(2)) ;
			paramEch.series[2].data.push(depData[o].PayGroupExpectIncome.toFixed(2)) ;
			paramEch.y.data.push(depData[o].ddesc) ;
		} ;
		paramEch.gridTop = '80' ;
		drawPayGroupBarChart(profitLossDep.id,paramEch) ;
}

/**
 * 科室次均费用对比图数据处理
 * @@param avgFeeDepEch
 * @void
 * @ Discription:
 * @paygroupAnalysis_dep.js
 */
function processAvgFeeDep(avgFeeDepEch) {
	var depData = avgFeeDepEch.data.dep ;
	// 图例边距和名称
	var legend = {"x":"40%","y":50, "data": ["次均费用"] } ;
	var paramEch = {"title":"科室次均费用对比图","subtitle":paramTabPage[tabId].desc,"legend":legend,"series":[{"data":[],"name":"次均费用"}],"y":{"data":[]}};
	for(var o in depData) {
		paramEch.series[0].data.push(depData[o].QuotaValue) ;
		paramEch.y.data.push(depData[o].ddesc) ;
	} ;
	paramEch.gridTop = '80' ;
	// 病组费用对比
	drawPayGroupBarChart("avgFeeDepEch",paramEch) ;
}

/**
 * 科室费用构成及对比图数据处理
 * @@param feeDepEch
 * @@param avgFeeAndFeeBqTab
 * @void
 * @ Discription:
 * @paygroupAnalysis_dep.js
 */
function processFeeDep(feeDepEch,avgFeeAndFeeBqTab) {
	var depData = feeDepEch.data.dep ;
	var legend = {"x":50,"y":50, "data": ['医疗费用', '护理费用','管理费用','医技费用','药品耗材费用'] } ;
	var paramEch = {"title":"科室费用构成及对比图","subtitle":paramTabPage[tabId].desc,"legend":legend,"series":[
	                                                              {"name":"医疗费用","type":"bar","data":[]},
	                                                              {"name":"护理费用","type":"bar","data":[]},
	                                                              {"name":"管理费用","type":"bar","data":[]},
	                                                              {"name":"医技费用","type":"bar","data":[]},
	                                                              {"name":"药品耗材费用","type":"bar","data":[]}
	                                                              ],"y":{"data":[]}};
	for(var o in depData) {
		paramEch.series[0].data.push(depData[o].MedFee) ;
		paramEch.series[1].data.push(depData[o].NursFee) ;
		paramEch.series[2].data.push(depData[o].ManageFee) ;
		paramEch.series[3].data.push(depData[o].TechFee) ;
		paramEch.series[4].data.push(depData[o].DrugMaterFee) ;
		paramEch.y.data.push(depData[o].ddesc) ;
	} ;
	paramEch.gridTop = '80' ;
	// 病组费用构成
	drawPayGroupBarChart("feeDepEch",paramEch,null,"stackbar") ;
	// 绘制表格
	drawAvgFeeAndFeeBqTab(avgFeeAndFeeBqTab,feeDepEch) ;
}

/**
 * 绘制会构成明细表格 
 * @@param avgFeeAndFeeBqTab
 * @@param feeDepEch
 * @void
 * @ Discription:
 * @paygroupAnalysis_dep.js
 */
function drawAvgFeeAndFeeBqTab(avgFeeAndFeeBqTab,feeDepEch) {
	var columns=[
	               	{"data": "ddesc","title":"科室"},
	               	{"data": "InCaseCnt","title":"病例数",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.InCaseCnt,0);
	           			}
	               	},
	               	{"data": "PayGroupOverFeeCnt","title":"费用超标病例数" ,
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.PayGroupOverFeeCnt,0);
	           			}
	               	},
	               	{"data": "AvgFee","title":"次均费用" ,
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.AvgFee,2);
	           			}
	               	},
	           		{"data": "DrugFee","title":"药品费用",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.DrugFee,2);
	           			}
	               	},
	           		{"data": "DrugRatio","title":"药占比(%)",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.DrugRatio,2);
	           			}
	               	},
	           		{"data": "AvgDays","title":"平均住院日",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.AvgDays,2);
	           			}
	               	},
	           		{"data": "MedFee","title":"医疗费用",
	           			"render": function(obj, type, full) {
	           				return formatNumPayGroup(full.MedFee,2) ;
	           			}
	           		},
	           		{"data": "NursFee","title":"护理费用",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.NursFee,2);
	           			}
	           		},
	           		{"data": "ManageFee","title":"管理费用",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.ManageFee,2);
	           			}
	           		},
	           		{"data": "TechFee","title":"医技费用",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.TechFee,2);
	           			}
	           		},
	           		{"data": "DrugMaterFee","title":"药品耗材费用",
	               		"render": function(obj, type, full) {
	               			return formatNumPayGroup(full.DrugMaterFee,2);
	           			}
	           		} ,
	           		{"data": "operation","title":"操作",
	           			"render": function(obj, type, full,meta) {
	           				return "<a data-rowindex='"+meta.row+"'>费用构成</a>" ;
	           			}
	           		}
  ];
	var param = drgUI.setAjaxData(tabId) ;
	var paramsDataTables={ordering:false,stateSave:true,tableTitle: param.pardrgCode+"病组次均费用、费用构成及对比情况表",columnDefs:[{"orderable": false,"targets": [ 0 ] }]};
	var table = $("#"+tabId+" #avgFeeAndFeeBqTab").dataTableBasic(columns,feeDepEch.data.dep,paramsDataTables) ;
	$("#"+tabId+" #avgFeeAndFeeBqTab_wrapper caption").html("<h5>"+param.pardrgCode+"病组次均费用、费用构成及对比情况表"+"</h5>") ;
	$("#"+tabId+" #avgFeeAndFeeBqTab tbody td").on("click","a",function(){
		var index = $(this).attr("data-rowindex");
    	var a = table.row( index ).data();//本期|同期|上期
    	var b = paramTabPage[tabId].target;//标杆
    	var c = ["ddesc","MedFee","NursFee","ManageFee","TechFee","DrugMaterFee","AvgFee"];
    	a.ddesc = "本期值";
    	costStructure(a,b,c);
	})
}
/**
 * 病例分布特征
 */
function findCaseDistributionFeatureDep(){
	$(document).bind("click",function(e){
       var target = $(e.target); 
       if(target.closest("#caseDistriParamDiv").length != 0){ 
           $('#'+tabId+'#caseDistriParamNav').addClass("open");
       }else{
    	   $('#'+tabId+'#caseDistriParamNav').removeClass("open"); 
       }
	});
	//判断监测时间是否为自定义，如果监测时间类型为自定义，参数范围默认选择本期
	if($("#searchcq").children().eq(2).find("div.ci a").eq(2).hasClass("active")){
		$('#'+tabId+' .caseDistriParamType').find("a").removeClass("active");
		$('#'+tabId+' .caseDistriParamType').find("a").eq(2).addClass("active");
	}
	//条件选择框点击事件
	$('#'+tabId+' #caseDistriParamDiv').off('click','a');
	$('#'+tabId+' #caseDistriParamDiv').on('click','a',function(){
		if($(this).attr('data-type')=="intervalCustom"){
			 $(this).css("display","none");
			 $('#'+tabId+' #intervalCustom').css("display","inline-block");
		 }
		 else if($(this).closest(".caseDistriParamInterval").length>0){
			 $('#'+tabId+' #intervalCustom').css("display","none");
			 $('#'+tabId+' #intervalCustom').prev().css("display","inline");
		 }
		//如果监测时间类型为自定义，参数范围只允许选择本期
		if($("#searchcq").children().eq(2).find("div.ci a").eq(2).hasClass("active")&&$(this).closest(".caseDistriParamType").length>0){
			$('#'+tabId+' ."caseDistriParamType"').find("a").removeClass("active");
			$('#'+tabId+' ."caseDistriParamType"').find("a").eq(2).addClass("active");
		}
		else{
			$(this).parent().find("a").removeClass("active");
			$(this).addClass("active");
		}
	});
	//区间个数input修改事件
	$('#'+tabId+' #intervalCustom').on('change','#intervalCustomInput',function(){
		$('#'+tabId+' .caseDistriParamInterval [data-type="intervalCustom"]').attr('data-value',$(this).val());   
	});
	var param = drgUI.setAjaxData(tabId) ;
	param.pType = "1" ;
	param.normalParam=$('#'+tabId+' .caseDistriParamType a.active').attr('data-value');
	param.interval=$('#'+tabId+' .caseDistriParamInterval a.active').attr('data-value');
	param.queryType='depDrg';
	var numberTest = /^\+?[1-9][0-9]*$/;
	if(param.interval==""||!numberTest.test(param.interval)){
		drgUI.error('请指定正确的区间个数!') ;
		return;
	}
	echartLoadingInit($('#'+tabId+' #probabilityDisEch'));
	echartLoadingInit($('#'+tabId+' #cumulativeDisEch'));
	$.post(contextPath + "/payGroup/getNormalDistributionData.dhc", param).done(function(result) {
		var data=result.data;
		var category=data.category;
		var axisCategory = jQuery.extend(true, [],category);
		axisCategory.pop();//移除最后一个元素
		var caseCnt=data.intervalFrequency;
		var cumulativeData=data.cumulativeDistribution;
		var probilityData=data.probilityDensity;
		var legendCommon=[];
		var seriesCommon=[];
		for(var o in caseCnt){
			legendCommon.push(caseCnt[o].depDesc);
			seriesCommon.push({name:caseCnt[o].depDesc,type:'bar',stack:'all',data:caseCnt[o].frequency});
		}
		var xAxis = [{type : 'category',data : axisCategory}];
		var yAxis = [{type : 'value',name : '病例数',splitNumber:5},
			        {type : 'value',name : '累积占比(%)',splitLine:{show:false}}];
		var series = jQuery.extend(true, [],seriesCommon);
		series.push({name:'累积占比(%)',type:'line',yAxisIndex: 1,data:cumulativeData,smooth:true});
		var legend=jQuery.extend(true, [],legendCommon);
		legend.push('累积占比(%)');
		var chartParams={autoWidth:true,autoHeight:'auto',heightRatio:0.8,pagemode:true,gridTop:80,gridBottom:80,gridRight:'12%',gridLeft:30};
		chartParams.formatterFunc=function (params) {
        	var str=category[params[0].dataIndex]+"~"+category[params[0].dataIndex+1]+ "<br/>";
        	for(var o in params){
        		if(params[o].data!=null){
        			str+=params[o].seriesName+":"+params[o].data+ "<br/>";
        		}
        	}
        	return str;
    	};
		barLineMixChartBasic($('#'+tabId+' #cumulativeDisEch'), legend,series,xAxis,yAxis,'科室病例住院费用直方图及正态累积分布图',paramTabPage[tabId].desc,chartParams);
		
		//概率密度
		var xAxisP = [{type : 'category',data : axisCategory}];
		var yAxisP = [{type : 'value',name : '病例数',splitNumber:5},
			        {type : 'value',name : '概率密度',splitLine:{show:false}, axisLabel : {formatter: function (value, index) {return Number(value).toExponential(2);}}}];
		var seriesP = jQuery.extend(true, [],seriesCommon);
		seriesP.push({name:'正态分布概率密度',type:'line',yAxisIndex: 1,data:probilityData,smooth:true});
		var legendP=jQuery.extend(true, [],legendCommon);
		legendP.push('正态分布概率密度');
		
		var chartParamsP={autoWidth:true,autoHeight:'auto',heightRatio:0.8,pagemode:true,gridTop:80,gridBottom:80,gridRight:'12%',gridLeft:30};
		chartParamsP.formatterFunc=function (params) {
			var str=category[params[0].dataIndex]+"~"+category[params[0].dataIndex+1]+ "<br/>";
        	for(var o in params){
        		if(params[o].seriesName=="正态分布概率密度"&&params[o].data!=null){
        			str+=params[o].seriesName+":"+Number(params[o].data).toExponential(2)+ "<br/>";
        		}
        		else if(params[o].data!=null){
        			str+=params[o].seriesName+":"+params[o].data+ "<br/>";
        		}
        		
        	}
        	return str;
    	};
		barLineMixChartBasic($('#'+tabId+' #probabilityDisEch'), legendP,seriesP,xAxisP,yAxisP,'科室病例住院费用直方图及正态分布概率密度曲线',paramTabPage[tabId].desc,chartParamsP);
		//参数调整框隐藏
		$('#'+tabId+' #caseDistriParamNav').removeClass("open");
	});
}